package com.lg.sso.client.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author by Mr. Li 2020/12/13 0:39
 */
@Controller
public class HelloController {

    @Value("${sso.server.url}")
    private String ssoServer;

    @Value("${sso.client1.url}")
    private String currentUrl;


    /**
     * 不需要登录 访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * 需要登录
     *
     * @return
     */
    @GetMapping("/employ")
    public String employ(Model model, HttpSession session, HttpServletRequest request,
                         @RequestParam(required = false, value = "token") String token) {

        // 判断 token 是否存在
        if (!StringUtils.isEmpty(token)) {
            // 发送远程服务，查询单点服务登录的用户名
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> result = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String body = result.getBody();
            // 设置session，实现通过登录验证
            session.setAttribute("loginUser", body);
        }

        // 判断用户是否登录
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            // 跳转到登录服务器
            String requestURI = request.getRequestURI();
            return "redirect:" + ssoServer + "?redirect_url=" + currentUrl + requestURI;
        }

        List<String> employs = new ArrayList<>();
        employs.add("张三");
        employs.add("李四");

        model.addAttribute("employ", employs);

        return "index";
    }

}
